package com.blue.core.util;

import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.core.auth.DigestUtil;


/**
 * 支付宝HTTP请求参数工具类
 * 
 * @author zhengj
 * @since 2014-12-5 1.0
 */
public class AlipayParamUtil
{
	private static Logger logger = LoggerFactory.getLogger(AlipayParamUtil.class);
	
	
	private AlipayParamUtil()
	{
	}
	
	
	/**
	 * 从对象生成HTTP请求参数
	 * 
	 * @param object
	 * @return
	 */
	public static String createParam(Object object, String key)
	{
		SortedSet<String> set = new TreeSet<String>();
		SortedSet<String> enSet = new TreeSet<String>();
		set.add("_input_charset=utf-8");
		enSet.add("_input_charset=utf-8");
		for (Method getter : ReflectionUtil.getterList(object.getClass()))
		{
			String fieldName = ReflectionUtil.field(getter);
			String column = ReflectionUtil.fieldToColumn(fieldName);
			
			try
			{
				String value = toStringValue(getter.invoke(object));
				if (value != null && !value.equals(""))
				{
					set.add(column + "=" + value);
					enSet.add(column + "=" + URLEncoder.encode(value, "UTF-8"));
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
		
		String md5 = DigestUtil.md5Hex(StringUtils.join(set, "&") + key);
		StringBuilder link = new StringBuilder(512);
		link.append("?");
		link.append(StringUtils.join(enSet, "&"));
		link.append("&sign_type=MD5&sign=").append(md5);

		logger.info("生成签名：{}", md5);
		
		return link.toString();
	}
	
	/**
	 * 从对象生成HTTP请求参数
	 * 
	 * @param object
	 * @return
	 */
	public static Map<String, String> createParamMap(Object object, String key)
	{
		Map<String, String> map = new HashMap<String, String>();
		SortedSet<String> set = new TreeSet<String>();
		set.add("_input_charset=utf-8");
		for (Method getter : ReflectionUtil.getterList(object.getClass()))
		{
			String fieldName = ReflectionUtil.field(getter);
			String column = ReflectionUtil.fieldToColumn(fieldName);
			
			try
			{
				String value = toStringValue(getter.invoke(object));
				if (value != null && !value.equals(""))
				{
					set.add(column + "=" + value);
					map.put(column, value);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
		
		String param = StringUtils.join(set, "&");
		String md5 = DigestUtil.md5Hex(param + key);
		
		map.put("sign_type", "MD5");
		map.put("sign", md5);

		logger.info("生成签名：{}", md5);
		
		return map;
	}
	
	/**
	 * 从HTTP请求参数生成对象
	 * 
	 * @param <T>
	 * @param clazz
	 * @param request
	 * @return
	 */
	public static <T> T fromParam(Class<T> clazz, String key, Map<String, String[]> param)
	{
		Map<String, String> map = new HashMap<String, String>();
		SortedSet<String> set = new TreeSet<String>();
		String sign = null;
		String signType = null;
		for (Map.Entry<String, String[]> entry : param.entrySet())
		{
			if (entry.getKey().equals("sign"))
			{
				sign = entry.getValue()[0];
				map.put(entry.getKey(), sign);
				continue;
			}
			if (entry.getKey().equals("sign_type"))
			{
				signType = entry.getValue()[0];
				map.put(entry.getKey(), signType);
				continue;
			}
			
			String[] values = entry.getValue();
			String value = (values.length == 1 ? values[0] : StringUtils.join(values, ","));
			
			if (value != null && !value.equals(""))
			{
				set.add(entry.getKey() + "=" + value);
				map.put(entry.getKey(), value);
			}
		}
		String md5 = DigestUtil.md5Hex(StringUtils.join(set, "&") + key);
		logger.info("来源签名：{} - {}", sign, signType);
		logger.info("验证签名：{}", md5);
		
		if (!md5.equals(sign))
			throw new IllegalArgumentException("签名验证失败");
		
		
		T obj = null;
		try
		{
			obj = clazz.newInstance();

			for (Method setter : clazz.getMethods())
			{
				if (!setter.getName().startsWith("set"))
					continue;
				
				String fieldName = ReflectionUtil.field(setter);
				String column = ReflectionUtil.fieldToColumn(fieldName);
				String strValue = map.get(column);
				if (strValue == null || strValue.equals(""))
					continue;
				
				Class<?> type = setter.getParameterTypes()[0];
				setter.invoke(obj, toObject(type, strValue));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	
	private static String toStringValue(Object value)
	{
		if (value == null)
			return null;
		
		if (value.getClass() == String.class)
			return (String)value;
		
		if (value.getClass() == Double.class)
			return MoneyUtil.format((Double)value);
		
		if (value instanceof Date)
			return DateUtil.formatDateTime((Date)value);
		
		return value.toString();
	}
	
	
	private static Object toObject(Class<?> clazz, String strValue)
	{
		if (strValue == null)
			return null;
		
		if (clazz == String.class)
			return strValue;
		
		if (clazz == Double.class)
			return Double.valueOf(strValue);
		
		if (clazz == Integer.class)
			return Integer.valueOf(strValue);
		
		if (clazz == Long.class)
			return Long.valueOf(strValue);
		
		if (clazz == Float.class)
			return Float.valueOf(strValue);
		
		if (clazz == Boolean.class)
			return Boolean.valueOf(strValue);
		
		if (clazz == Date.class)
			return DateUtil.parseDateTime(strValue);
		
		return strValue;
	}
	
}
